package org.annoflow.filter.xss;

import java.util.HashMap;

import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;

public class XSSFilter implements FilterPoint {

	@Override
	public String getFilterCode() {
		return "org.annoflow.filter.xss.XSSFilter.runFilter($args);";
	}
	
	public static void runFilter(Object[] args) throws Exception {
		for (Object arg : args) {
			
			//First check if it's a string
			if (arg instanceof String) {
				if (isInvalidHTML((String)arg)) {
					throw new Exception();
				}
			}
			
			//Next check if there's a policy on the object being passed in
			PolicyType policy = null;
			if ((policy = PolicyManager.lookupObjectPolicy(arg)) != null) {
				HashMap<String,String> context = new HashMap<String, String>();
				context.put("target", "html");
				policy.assess(context);
			}
			
			//Finally check if there's a policy on any of the object's fields
			HashMap<Object,PolicyType> fields = null;
			if((fields = PolicyManager.lookupParentPolicy(arg)) != null) {
				HashMap<String,String> context = new HashMap<String, String>();
				context.put("target", "html");
				for (Object field : fields.keySet()) {
					fields.get(field).assess(context);
				}
			}
		}
	}
	
	private static boolean isInvalidHTML(String arg) {
		return arg.contains("<script>") || arg.contains("</script>");
	}

	@Override
	public String getReturnFilterCode() {
		return null;
	}

}
